<?php
/*
新增数据库表
CREATE TABLE IF NOT EXISTS `think_cpclevel` (
  `member_id` int(11) NOT NULL COMMENT '拿提成的会员ID',
  `member_level` int(11) NOT NULL COMMENT '当前拿提成的会员级别',
  `aff_member_level` int(11) NOT NULL COMMENT '当前消费的会员级别',
  `dateline` varchar(30) NOT NULL COMMENT '拿提成的时间'
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='国省市三级分成扩展表，用于记录会员拿提成次数';



CREATE TABLE IF NOT EXISTS `think_cpcmember` (
  `member_id` int(11) NOT NULL COMMENT '用户ID',
  `level` int(2) NOT NULL DEFAULT '0' COMMENT '等级',
  `datetime` int(11) NOT NULL COMMENT '升级时间'
) ENGINE=MyISAM DEFAULT CHARSET=gbk;
*/


class Cpclevel{
	public $money;
	public $order;
	public $site_id;
	public $userlist;
	public $orderdb;
	public $memberdb;
	public $member_id;
	public $error = array();
	//构造函数
	public function Cpclevel($order_id = 0, $site_id = 0, $member_id = 0){
		$this->memberdb = D('Member');
		$this->orderdb = D('Order');
		$this->saledb = M('Sale');
		$this->money = $this->getmoney();
		$this->site_id = $site_id;
		
		$db = M('Affiliatesetting');
		$affsetting = $db -> where(array('site_id' => $this->site_id,'classname' => 'Cpclevel')) -> find();
		$this -> affsettingarr = unserialize($affsetting['value']);
		
		$this->order = $this->orderdb -> where(array('id' => $order_id)) -> find();
		
		$this->member_id = $member_id > 0? $member_id: $this->order['member_id'];
		if(!$this->order){
			$this->error['info'] = '订单不存在！';
		}
		
		$this->updateUserLevel();
	}
	//创建设置项表单
	public function createform(){
		
		$db = M('Affiliatesetting');
		
		$ret = array ('level' => array ( 0,0,0),'levelname' => array ( 0 => '全国代理', 1 => '省代理', 2 => '市代理'), 'levelbuy' => array ( 0 => '0', 1 => '0', 2 => '0'), 'levelaff' => array ( 0 => '0', 1 => '0', 2 => '0'), 'levelaff_' => array ( 0 => '0', 1 => '0', 2 => '0'), 'rlevel' => array ( 0 => '0', 1 => '0', 2 => '0'), 'changelevel' => '恭喜您升级成为：@levelname@');
		
		
		
		$ret = $db -> where(array('site_id' => $this->site_id,'classname' => 'Cpclevel')) -> find();
		$ret = unserialize($ret['value']);
		//F('ret',$ret);
		$html = '<style>#Cpclevel td{padding:5px;}</style><table id="Cpclevel" border="1" cellspacing="0" cellpadding="5" width="100%">
  <tr>
    <th align="center" style="text-align:center; width:100px;">级别</th>
	<th align="center" style="text-align:center;">级别名称</th>
	<th align="center" style="text-align:center;">最低消费</th>
    <th align="center" style="text-align:center;">拿提成次数(国,省,市)</th>
  </tr>
  <tr>
    <td align="center" valign="middle">1</td>
	<td align="center" valign="middle"><input type="text" name="levelname[]" value="'.$ret['levelname'][0].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelbuy[]" value="'.$ret['levelbuy'][0].'" /></td>
    <td align="center">
	
	<input type="text" name="rlevel[0][]" value="'.$ret['rlevel'][0][0].'" />
	<input type="text" name="rlevel[0][]" value="'.$ret['rlevel'][0][1].'" />
	<input type="text" name="rlevel[0][]" value="'.$ret['rlevel'][0][2].'" />
	</td>
  </tr>
  <tr>
    <td align="center" valign="middle">2</td>
	<td align="center" valign="middle"><input type="text" name="levelname[]" value="'.$ret['levelname'][1].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelbuy[]" value="'.$ret['levelbuy'][1].'" /></td>
    <td align="center">
	<input type="text" name="rlevel[1][]" value="'.$ret['rlevel'][1][0].'" />
	<input type="text" name="rlevel[1][]" value="'.$ret['rlevel'][1][1].'" />
	<input type="text" name="rlevel[1][]" value="'.$ret['rlevel'][1][2].'" />
	
	</td>
  </tr>
  <tr>
    <td align="center" valign="middle">3</td>
	<td align="center" valign="middle"><input type="text" name="levelname[]" value="'.$ret['levelname'][2].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelbuy[]" value="'.$ret['levelbuy'][2].'" /></td>
    <td align="center">
	
	<input type="text" name="rlevel[2][]" value="'.$ret['rlevel'][2][0].'" />
	<input type="text" name="rlevel[2][]" value="'.$ret['rlevel'][2][1].'" />
	<input type="text" name="rlevel[2][]" value="'.$ret['rlevel'][2][2].'" />
	
	</td>
  </tr>
  
</table>
<br>

<table cellpadding="0" class="Threelevel" cellspacing="0" border="1" width="100%">

  
  
  <tr>
    <td align="center" valign="middle" style="width:150px;">会员升级后通知信息</td>
    <td align="left" colspan="2"><input style="width:100%" type="text" name="changelevel" value="'.$ret['changelevel'].'" /><br>
等级名称@levelname@
</td>
  </tr>
  
 
 
  
</table>
<br>

<style>.Threelevel td{padding:5px;}</style><table class="Threelevel" border="1" cellspacing="0" cellpadding="5" width="100%">
  <tr>
    <th align="center" style="text-align:center; width:100px;">级别</th>
    <th align="center" style="text-align:center;">分成比例</th>
  </tr>
  
  <tr>
    <td align="center" valign="middle">1</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][0].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">2</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][1].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">3</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][2].'" />%</td>
  </tr>
  
</table>
';

        return $html;
	}
	
	//保存设置项
	public function saveform(){
		if(isset($_POST['level'])){
			$data['classname'] = 'Cpclevel';
			$data['value'] = serialize($_POST);
			$data['site_id'] = $this->site_id;
			$db = M('Affiliatesetting');
			
			//dump($data);
			$ret = $db -> where(array('site_id' => $data['site_id'],'classname' => $data['classname'])) -> find();
			if($ret){
				$saveret = $db -> where(array('site_id' => $data['site_id'],'classname' => $data['classname'])) -> data(array('value' => $data['value'])) -> save();
			}else{
				$saveret = $db -> data($data) -> add();
			}
			if($saveret){
				return true; 
			}else{
				$this->error['info'] = $db -> getLastSql();
				return false;
			}
			
		}
	}
	
	
	public function updateUserLevel(){
		$db = M('Affiliatesetting');
		$cmdb = M('Cpcmember');
		
		$affsetting = $db -> where(array('site_id' => $this->site_id,'classname' => 'Cpclevel')) -> find();
		$affsettingarr = unserialize($affsetting['value']);
		//查询用户
		$memberInfo = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		//升级为基本分销等级
		$cml = $cmdb -> where(array('member_id' => $this->member_id)) -> find();
		if(!$cml){
			$cmldata['member_id'] = $this->member_id;
			$cmldata['datetime'] = time();
			$cmldata['level'] = 0;
			$cmdb -> data($cmldata) -> add();
		}
		$total = $this->orderdb -> where(array('member_id' => $this->member_id, 'status' => 2)) -> sum('total');
		$rlevel = 0;
		
		
		foreach(array_reverse($affsettingarr['levelbuy']) as $k => $v){
			if($total >= $v){
				$rlevel = $k + 2;
			}
		}
		
		
		$data['level'] = $rlevel;
		if($data['level'] < $memberInfo['level']){
			$data['level'] = $memberInfo['level'];
			$data['time'] = time();
		}
		//$ret = $this->memberdb -> where(array('id' => $memberInfo['id'])) -> data($data) -> save();
		$cmdb -> data($data) -> save();
		$mtmdb = M('Member_member');
		$mtmdb -> where(array('smember_id' => $memberInfo['id'])) -> data($data) -> save();
	}
	
	//获取等级
	public function getMemberLevel($member_id = 0){
		if($member_id == 0){$member_id = $this->member_id;}
		$cmdb = M('Cpcmember');
		return $cmdb -> where(array('member_id' => $member_id)) -> getField('level');
	}
	
	//获取等级名称
	public function getLevelName(){
		$memberInfo = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$namelist = $this -> affsettingarr['levelname'];
		$namelist[] = '普通会员';
		$namelist[] = '普通会员';
		$namelist = array_reverse($namelist);
		return $namelist[$memberInfo['level']];
	}
	
	//获取等级名称列表
	public function getLevelNameList(){
		$memberInfo = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$namelist = $this -> affsettingarr['levelname'];
		//$namelist[] = $this -> affsettingarr['levelnamebase'];
		$namelist[] = '普通会员';
		$namelist[] = '普通会员';
		$namelist = array_reverse($namelist);
		return $namelist;
	}
	//获取父子级会员数组8级
	public function getUserArr($pid=0,$arr=array(), $deep = 0){
		$re=$this->memberdb->where(array('id'=>$pid,'site_id'=>$this->site_id))->find();
		//8级返回
		if($deep == 3){return $arr;}
		if(!is_array($re)){
			return $arr;
		}else{
			$re['deep'] = $deep + 1;
			//if($re['level'] > 0){
				$re['level'] = $this->getMemberLevel($re['id']);
			    $arr[]=$re;
			//}
			$deep ++;
			return $this->getUserArr($re['pid'],$arr, $deep);
		}
	}
	

	
	
	
	
	//获取VIP分成用户列表(需要分成的用户列表)
	public function getuserlist(){
		$ordermember = $this->memberdb -> where(array('id' => $this->order['member_id'])) -> find();
		$affsettingarr = $this -> affsettingarr;
		$list = $this -> getUserArr($ordermember['pid']);
		//$affcountconfig = array_reverse(explode(',',$affsettingarr['rlevel']));
		$cpcdb = M('Cpclevel');
		
		$productList = $this->getmoney();
		$total = 0;
		foreach($productList as $key => $val){
			$total += $val['total'];
		}
		
		
		foreach($list as $k => $v){
			
			if($v['level'] >= 2){
				
				$econfig = array();
				$configc = array_reverse($this -> affsettingarr['rlevel']);
				foreach(array_reverse($configc[$v['level'] - 2]) as $key => $val){
					$cofnigarr = explode(':', $val);
					if($cofnigarr[0] <= $total){
						$econfig = explode(',', $cofnigarr[1]);
					}
				}
				
				$map['member_id'] = $v['id'];
				$map['member_level'] = $v['level'];
				$map['deep'] = $v['deep'];
				$map['aff_member_level'] = array('egt', $total);
				$cpccount = $cpcdb -> where($map) -> count();
				
				
				
				if($cpccount < $econfig[$v['deep'] - 1] || $econfig[$v['deep'] - 1] == 0){
					$list[$k]['aff'] = $affsettingarr['level'][$k];
				}else{
					$list[$k]['aff'] = 0;
				}
			}else{
				$list[$k]['aff'] = 0;
			}
		}
		return $list;
	}
	
	
	
	
	
	
	public function insertlog(){
		$db = M('Member_account_log');
		$productList = $this->getmoney();
		$userList = $this->getuserlist();
		$aff_member_level = $this->memberdb -> where(array('id' => $this->member_id)) ->getField('level');
		$cpcdb = M('Cpclevel');
		foreach($userList as $k => $v){
			$money = 0;
			$total = 0;
			foreach($productList as $key => $val){
				
				
				$map['member_id'] = $v['id'];
				$map['order_id'] = $this->order['id'];
				$map['product_id'] = $val['product_id'];
				if($db -> where($map) -> find()){
					continue;
				}
				
				
				
				
				$total += $val['total'];
				$data['member_id'] = $v['id'];
				$data['user_id'] = 0;
				$data['pdstate'] = 3; //类型3为分成
				$data['dateline'] = time();
				$data['changenum'] = round($val['aff_money']*$v['aff']/100,2);
				$data['order_id'] = $this->order['id'];
				$data['order_sn'] = $this->order['ordernumber'];
				$data['product_id'] = $val['product_id'];
				$data['num'] = $val['num'];
				$data['site_id'] = $this->site_id;
				$data['attr'] = $val['attr'];
				$data['remark'] = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$data['changenum'];
				$data['goodsMoney'] = $val['total'];
				if($data['changenum'] > 0){
					$money += $data['changenum'];
					//是否需要审核分成
					$flag = false;
					if($val['affpass'] > 0){
						$hbcount = ceil($data['changenum'] / 200);
						$hbmoney = $data['changenum'];
						for($i = 0; $i < $hbcount; $i++){
							$sendmoney = 200;
							if($hbmoney > 200){
							    $hbmoney = $hbmoney - 200;
							}else{
								$sendmoney = $hbmoney;
							}
							$result = sendBonus($v['openid'],$sendmoney,$this->site_id);
						}
					}
					$db -> data($data) -> add();
					
					
			    }else{
					$total = 0;
				}
			}
			if($total > 0){
				$cpcdata['member_id'] = $v['id'];
				$cpcdata['member_level'] = $v['level'];
				$cpcdata['deep'] = $v['deep'];
				$cpcdata['aff_member_level'] = $total;
				$cpcdb -> add($cpcdata);
			}
			
			
			if($money > 0){
				//记录次数
				
				//信息通知
				$msg = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
				sendWXMsg($v['openid'], $msg);
			}
		}
		
	}
	
	//撤消一个分成
	public function loggoback(){
		
	}
	
	//获取分成总额
	public function getmoney(){
		return $this -> saledb -> where(array('order_id' => $this->order['id'])) -> Field('(aff_money*num) as aff_money,product_id,total,num,attr,affpass') -> select();
	}
	public function sendMsg(){}
	//返回错误信息
	public function getError(){
		return $this->error['info'];
	}
	
	
	public function getAffData(){
		$ret = array();
		return $ret;
	}
	
}